<?php

namespace App\Model;

use App\BaseModel;

class WineProductScore extends BaseModel
{
    protected $table = "wine_product_score";

    protected $appends = ['expert_scores'];

    protected $hidden = ['scores'];

    protected $fillable = [
        'product_id',
        'user_id',
        'averageScore',
        'vintage',
        'type'
    ];

    public function scores()
    {
        return $this->hasMany('App\Model\WineProductExpertScore','score_id','id');
    }

    public function sameScores()
    {
        return $this->hasMany('App\Model\WineProductScore','product_id','product_id')
            ->where('type','=','same');
    }

    public function getSameProductScoresAttribute()
    {
        return $this->sameScores;
    }

    public function getExpertScoresAttribute()
    {
        return $this->scores;
    }

    //更新平均分
    public function updateAverageScore()
    {
        if($this->scores()->count() > 0) {
            $this->averageScore = $this->scores()->sum('score') / $this->scores()->count();
            $this->save();
        }
    }
}
